package com.example.spring.security.demo.service;

import com.example.spring.security.demo.entity.MyUserDetails;
import com.example.spring.security.demo.entity.ResponseResult;
import com.example.spring.security.demo.entity.User;
import com.example.spring.security.demo.utils.JwtUtil;
import com.example.spring.security.demo.utils.RedisCache;
import com.example.spring.security.demo.utils.UserUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;

/**
 * @ClassName UserService
 * @Description
 * @Author lichuanqi
 * @Date 2022/5/14 12:50
 * @Version 1.0
 **/
@Service
public class UserService {

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private RedisCache redisCache;

    public ResponseResult login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        //authenticate会调用UserDetailsService来获取凭证
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        MyUserDetails myUserDetails = (MyUserDetails) authenticate.getPrincipal();
        String userIdStr = myUserDetails.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userIdStr);
        HashMap<String, String> resultMap = new HashMap<>();
        resultMap.put("token", jwt);
        redisCache.setCacheObject(UserUtils.getUserIdCacheKey(userIdStr), myUserDetails);
        return new ResponseResult(200,"登录成功", resultMap);
    }

    public ResponseResult logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        MyUserDetails userDetails = (MyUserDetails) authentication.getPrincipal();
        String redisKey = UserUtils.getUserIdCacheKey(userDetails.getUser().getId().toString());
        redisCache.deleteObject(redisKey);
        return new ResponseResult(200, userDetails.getUsername()+",已注销");
    }
}
